const Storage = require('../../utils/storage')

Page({
  data: {
    doctor: {
      avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
      name: '张医生',
      department: '内科-心血管科',
      title: '主任医师',
      hospital: '协和医院',
      hospitalId: '',
      hospitalLevel: '三甲',
      rating: 4.9,
      consultCount: '1.2万',
      tags: ['耐心', '专业', '细致', '经验丰富', '态度和蔼'],
      intro: '张医生在心血管疾病的诊断和治疗方面有丰富的经验，擅长冠心病、高血压、心律失常等疾病的治疗。',
      isOnline: true,
      isCertified: true,
      videoPrice: 0,
      expertise: '擅长各类心血管疾病的诊断和治疗，尤其在冠心病、高血压、心律失常等方面有丰富经验。在心血管疾病的预防、诊断和治疗方面有独到见解。',
      education: '1985-1992 北京医科大学临床医学系\n1992-1995 北京协和医院心内科住院医师\n1995-1998 北京协和医院心内科主治医师'
    },
    reviews: [],
    showIntroPopup: false,
    reviewTags:[]
  },

  onLoad(options) {
    this.data.doctor.id = options.id;
    this.fetchDoctorDetail(options.id);
    // 先尝试从缓存获取标签数据
    const cachedTags = Storage.getDoctorTags(options.id);
    if (cachedTags) {
      this.setData({ 'doctor.reviewTags': cachedTags });
    } else {
      this.fetchReviewTags(options.id);
    }
    
    this.fetchReviews(options.id);
    this.getVideoConsultationPrice(options.doctorId);
  },

  fetchDoctorDetail(id) {
    wx.request({
      url: `https://your-api-domain/api/v1/doctors/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          this.setData({ doctor: res.data.data });
        } else {
          
        }
      },
      fail: (err) => {
        
      }
    });
  },

  fetchReviewTags(doctorId) {
    wx.request({
      url: `https://your-api-domain/api/v1/doctors/${doctorId}/review-tags`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const tags = res.data.data;
          // 缓存标签数据
          Storage.setDoctorTags(doctorId, tags);
          this.setData({ 'doctor.reviewTags': tags });
        } else {
          
          this.useMockReviewTags(doctorId);
        }
      },
      fail: (err) => {
        
        this.useMockReviewTags(doctorId);
      }
    });
  },

  useMockReviewTags(doctorId) {
    const mockTags = [
      { id: 'tag1', tag: '头痛', count: 12 },
      { id: 'tag2', tag: '胸闷', count: 8 },
      { id: 'tag3', tag: '眩晕', count: 6 },
      { id: 'tag4', tag: '高血压', count: 15 },
      { id: 'tag5', tag: '失眠', count: 9 }
    ];
    Storage.setDoctorTags(doctorId, mockTags);
    this.setData({ 'doctor.reviewTags': mockTags });
  },

  fetchReviews(doctorId) {
    wx.request({
      url: `https://your-api-domain/api/v1/doctors/${doctorId}/reviews`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const reviews = res.data.data.map(review => ({
            ...review,
            phone: review.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
            satisfactionText: this.getSatisfactionText(review.satisfaction),
            satisfactionClass: this.getSatisfactionClass(review.satisfaction),
            formattedDate: this.formatDate(review.date)
          }));
          this.setData({ reviews });
        } else {
          
          this.useMockReviews();
        }
      },
      fail: (err) => {
        
        this.useMockReviews();
      }
    });
  },

  // 添加满意度文本转换方法
  getSatisfactionText(satisfaction) {
    switch(satisfaction) {
      case 'satisfied':
        return '满意';
      case 'average':
        return '一般';
      case 'unsatisfied':
        return '不满意';
      default:
        return '未评价';
    }
  },

  // 添加满意度样式类转换方法
  getSatisfactionClass(satisfaction) {
    switch(satisfaction) {
      case 'satisfied':
        return 'satisfaction-good';
      case 'average':
        return 'satisfaction-average';
      case 'unsatisfied':
        return 'satisfaction-bad';
      default:
        return '';
    }
  },

  useMockReviews() {
    const mockReviews = Array.from({ length: 10 }, (_, index) => ({
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      date: this.getRandomDate(),
      content: '医生很专业，讲解详细，态度很好。',
      consultation: '最近工作压力大导致经常性头痛，医生详细询问了症状。',
      consultation_type: ['头痛', '胸闷', '眩晕', '高血压', '失眠'][Math.floor(Math.random() * 5)],
      satisfaction: ['satisfied', 'average', 'unsatisfied'][Math.floor(Math.random() * 3)],
      consultation_id: `C${String(index + 1).padStart(3, '0')}`
    }));

    const processedReviews = mockReviews.map(review => ({
      ...review,
      phone: review.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
      satisfactionText: this.getSatisfactionText(review.satisfaction),
      satisfactionClass: this.getSatisfactionClass(review.satisfaction),
      formattedDate: this.formatDate(review.date)
    }));

    this.setData({ reviews: processedReviews });
  },

  // 生成随机日期（最近30天内）
  getRandomDate() {
    const today = new Date();
    const thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));
    const randomTime = thirtyDaysAgo.getTime() + Math.random() * (today.getTime() - thirtyDaysAgo.getTime());
    return new Date(randomTime).toISOString().split('T')[0];
  },

  formatDate(dateString) {
    const date = new Date(dateString);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },

  onViewAllIntro() {
    this.setData({ showIntroPopup: true });
  },

  closeIntroPopup() {
    this.setData({ showIntroPopup: false });
  },

  onIntroPopupChange(e) {
    const { visible } = e.detail;
    if (!visible) {
      this.closeIntroPopup();
    }
  },

  onViewAllReviews() {
    // 默认使用第一个标签
    const firstTagId = this.data.doctor.reviewTags[0]?.id;
    wx.navigateTo({
      url: `/pages/reviews/index?doctorId=${this.data.doctor.id}&tagId=${firstTagId}`
    });
  },

  onTagTap(e) {
    const tagId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/reviews/index?doctorId=${this.data.doctor.id}&tagId=${tagId}`
    });
  },

  onHospitalDetail() {
    const hospitalId = this.data.doctor.hospitalId || 'H001';
    wx.navigateTo({
      url: '/pages/hospital/detail?hospitalId=' + hospitalId
    });
  },

  getVideoConsultationPrice(doctorId) {
    wx.request({
      url: 'your_api_base_url/api/doctor/video-price',
      method: 'GET',
      data: {
        doctorId: doctorId
      },
      success: (res) => {
        if (res.data && res.data.success) {
          this.setData({
            'doctor.videoPrice': res.data.data.price
          });
        } else {
          this.setData({
            'doctor.videoPrice': this.getMockVideoPrice()
          });
        }
      },
      fail: (error) => {
        
        this.setData({
          'doctor.videoPrice': this.getMockVideoPrice()
        });
      }
    });
  },

  getMockVideoPrice() {
    const title = this.data.doctor.title;
    let price = 0;
    
    switch(title) {
      case '主任医师':
        price = 300;
        break;
      case '副主任医师':
        price = 200;
        break;
      case '主治医师':
        price = 150;
        break;
      default:
        price = 100;
    }
    
    return price;
  },

  onVideoConsult() {
    wx.showToast({
      title: '正在开发中...',
      icon: 'none'
    });
  }
}); 